%%%-------------------------------------------------------------------
%%% @author Rain
%%% @doc mysql数据库池
%%% @end
%%%-------------------------------------------------------------------
-module(mysql_pool).
-author("Rain").
-include("db.hrl").

%% API
-export([start_pool/2]).
-export([query/3]).


%% @doc 启动mysql进程池
%% 必须搭配配置了config的环境使用。
start_pool(SupPid, DBTypeList) ->
    Fun =
        fun(DBType) ->
            ChildSpec = child_spec(DBType),
            {ok, _} = game_util:start_child(SupPid, ChildSpec)
        end,
    lists:foreach(Fun, DBTypeList),
    ok.

%% @doc 服务名称
pool_serv_name(DBType) ->
    list_to_atom("mysql_" ++ DBType).

child_spec(DBType) ->
    {WorkerArgs, SizeArgs} = db_config:get_db_conn_args(DBType),
    PoolName = pool_serv_name(DBType),
    PoolArgs = [{name, {local, PoolName}}, {worker_module, mysql}] ++ SizeArgs,
    ChildSpec = poolboy:child_spec(PoolName, PoolArgs, WorkerArgs),
    ChildSpec.

%% @doc 通过进程池随机进程数据库查询
query(DBType, Sql, Params) ->
    PoolName = pool_serv_name(DBType),
    Conn = poolboy:checkout(PoolName, true, ?MYSQL_QUERY_TIMEOUT),
    try
        QueryReturn = mysql:query(Conn, Sql, Params),
        ok = poolboy:checkin(PoolName, Conn),
        QueryReturn
    catch
        Class: Reason: Stack ->
        ?LOG_ERROR("===================DB QUERY ERROR ==================~n
                    Class ~p Reason ~p~n
                    Stack ~p~n
                    ", [Class, Reason, Stack]),
        ok = poolboy:checkin(PoolName, Conn),
        throw({Class, Reason})
    end.

